package softisoft.impcontacts;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

public class CSVParser {
	
	public static String filePath = "";
	public static String[] header;
	public static String[] contactInfo;
	public static BufferedReader br;
	public static String erorr = "";
	
	public static ArrayList<Contact> contacts = new ArrayList<Contact>();
	
	public String name;
	public String phone;
	public String email;
	
	
	public static boolean openReader(){
		try {
			FileInputStream fstream = new FileInputStream(filePath);
			Reader reader = new InputStreamReader(fstream, "UTF-16");
			br = new BufferedReader(reader);
			return true;
		} catch (Exception e) {
			erorr = e.getMessage();
			return false;
		}
	}
	
	public static int read(){ 
		int i = 0;
		try {
			String strLine;
			while ((strLine = br.readLine()) != null)   {
				strLine=strLine.replaceAll("\"","");
				CSVParser.parseLine(strLine,i);
				i++;
			}
		} catch (Exception e) {
			erorr = e.getMessage();
			return 0;
		}
		return i;
		
	}
	
	public static void parseLine(String strLine,int pozicija){
		if (pozicija == 0) {
			header = strLine.split(",");
		}
		else{
			contactInfo = strLine.split(",");
			Contact c = new Contact();
			c.setName(contactInfo[1] + " " +  contactInfo[3]);
			if (contactInfo.length >=16){
				c.setPhone(contactInfo[13]); 
				c.setEmail(contactInfo[15]);
			}
			else if (contactInfo.length >=13){
				c.setPhone(contactInfo[13]); 
			}
			contacts.add(c);
		}
	}
	
	public static void closeReader(){
		try {
			br.close();
		} catch (Exception e) {
			erorr = e.getMessage();
		}
	}
	
}
